package com.neusoft.nep.admin.controller;

import com.neusoft.nep.admin.entity.AqiData; // Assuming AqiData is in entity package
import com.neusoft.nep.grid.entity.Fankui; // Assuming Fankui is an entity, adjust package if different
import com.neusoft.nep.common.AqiDataFileUtil; // Import the utility class for AqiData (fankui.txt)
import com.neusoft.nep.common.FileUtils; // Import the utility class for reading Map objects (FankuiData.txt)

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AQIAdminViewController {

    @FXML
    private TableView<AqiData> aqiTable;

    @FXML
    private TableColumn<AqiData, String> idColumn;
    @FXML
    private TableColumn<AqiData, String> provinceColumn;
    @FXML
    private TableColumn<AqiData, String> cityColumn;
    @FXML
    private TableColumn<AqiData, String> levelColumn;
    @FXML
    private TableColumn<AqiData, String> dateColumn;
    @FXML
    private TableColumn<AqiData, String> timeColumn;
    @FXML
    private TableColumn<AqiData, String> gridStaffColumn;
    @FXML
    private TableColumn<AqiData, String> reporterColumn;
    @FXML
    private TableColumn<AqiData, String> actionColumn; // This is the "操作" column


    @FXML
    private ChoiceBox<String> cmbProvince2;
    @FXML
    private ChoiceBox<String> cmbCity2;
    @FXML
    private TextField txt_address;
    @FXML
    private Button btn_grid;
    @FXML
    private Button queryButton;
    @FXML
    private Button clearButton;
    @FXML
    private DatePicker datePicker;
    @FXML
    private Button saveButton;

    private Map<String, List<String>> provinceMap = new HashMap<>();

    // --- THIS MASTER LIST IS CRUCIAL ---
    private ObservableList<AqiData> masterAqiData = FXCollections.observableArrayList();
    // ------------------------------------

    @FXML
    public void initialize() {
        // Set column resize policy
        aqiTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        // Initialize province and city choice boxes
        provinceMap.put("辽宁省", List.of("沈阳市", "大连市", "铁岭市", "抚顺市"));
        provinceMap.put("山西省", List.of("太原市", "吕梁市", "大同市", "运城市"));
        provinceMap.put("湖南省", List.of("长沙市", "湘潭市", "衡阳市", "怀化市"));
        provinceMap.put("吉林省", List.of("长春市", "吉林市", "四平市"));

        cmbProvince2.setItems(FXCollections.observableArrayList(provinceMap.keySet()));
        cmbProvince2.getSelectionModel().clearSelection();
        cmbProvince2.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) -> {
                    if (newValue != null) {
                        List<String> cities = provinceMap.get(newValue);
                        ObservableList<String> cityList = FXCollections.observableArrayList(cities);
                        cmbCity2.setItems(cityList);
                        cmbCity2.getSelectionModel().clearSelection();
                    } else {
                        cmbCity2.setItems(FXCollections.observableArrayList());
                    }
                });

        // Initialize table columns with CellValueFactory
        idColumn.setCellValueFactory(cellData ->
                new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getId()));
        provinceColumn.setCellValueFactory(cellData ->
                new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getProvince()));
        cityColumn.setCellValueFactory(cellData ->
                new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getCity()));
        levelColumn.setCellValueFactory(cellData ->
                new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getLevel()));
        dateColumn.setCellValueFactory(cellData ->
                new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getDate()));
        timeColumn.setCellValueFactory(cellData ->
                new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getTime()));
        gridStaffColumn.setCellValueFactory(cellData ->
                new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getGridStaff()));
        reporterColumn.setCellValueFactory(cellData ->
                new javafx.beans.property.ReadOnlyStringWrapper(cellData.getValue().getReporter()));

        // Set action for "操作" (Action) column (Detail button)
        actionColumn.setCellFactory(param -> new TableCell<AqiData, String>() {
            private final Button detailButton = new Button("详情");

            { // This block runs for each cell
                detailButton.getStyleClass().add("detail-button");
                detailButton.setOnAction(event -> {
                    AqiData data = getTableView().getItems().get(getIndex());
                    try {
                        FXMLLoader fxmlLoader = new FXMLLoader();
                        URL url = getClass().getResource("../view/AQIAdminStepView.fxml");
                        if (url == null) {
                            System.err.println("AQIAdminStepView.fxml not found! Check path: ../view/AQIAdminStepView.fxml");
                            return;
                        }
                        fxmlLoader.setLocation(url);
                        Parent root = fxmlLoader.load();

                        Stage dialog = new Stage();
                        dialog.setTitle("AQI数据列表/AQI数据详情");
                        dialog.initModality(Modality.APPLICATION_MODAL);
                        dialog.initOwner(((Node) event.getSource()).getScene().getWindow());
                        Scene scene = new Scene(root);
                        dialog.setScene(scene);

                        AQIAdminStepViewController controller = fxmlLoader.getController();
                        if (controller != null) {
                            controller.setData(data);
                            controller.setDialog(dialog);
                        }
                        dialog.showAndWait();
                    } catch (IOException ex) {
                        System.err.println("加载AQIAdminStepView.fxml文件时出错: " + ex.getMessage());
                        ex.printStackTrace();
                        Alert errorAlert = new Alert(Alert.AlertType.ERROR);
                        errorAlert.setTitle("错误");
                        errorAlert.setHeaderText("加载详情页面失败");
                        errorAlert.setContentText("无法打开AQI数据详情页面。请检查文件路径和日志。");
                        errorAlert.showAndWait();
                    }
                });
            }

            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    setGraphic(detailButton);
                }
            }
        });

        // --- CORE LOGIC TO LOAD AND DISPLAY DATA ---
        List<AqiData> dataToLoadIntoTable = new ArrayList<>();

        // 1. Attempt to read Fankui data generated by DataWriter (FankuiData.txt)
        Map<String, Fankui> fankuiMap = FileUtils.readMapObject("Fankui3.txt");

        if (fankuiMap != null && !fankuiMap.isEmpty()) {
            System.out.println("从 FankuiData.txt 加载数据并转换为 AqiData。");
            // Convert Fankui objects to AqiData objects
            for (Fankui fankui : fankuiMap.values()) {
                String dateTime = fankui.getTime(); // This field in Fankui contains "YYYY-MM-DD HH:MM"
                String datePart = "";
                String timePart = "";
                if (dateTime != null && dateTime.contains(" ")) {
                    String[] dtParts = dateTime.split(" ", 2); // Split into date and time parts
                    datePart = dtParts[0];
                    timePart = dtParts[1];
                } else {
                    // If no space, assume the whole string is date, time is empty
                    datePart = dateTime != null ? dateTime : "";
                    timePart = "";
                }

                // 'gridStaff' field is not directly available in Fankui, use a placeholder
                dataToLoadIntoTable.add(new AqiData(
                        fankui.getCode(),        // id (Fankui's code maps to AqiData's id)
                        fankui.getSheng(),       // province
                        fankui.getShi(),         // city
                        fankui.getLevel(),       // level
                        datePart,                // date extracted from Fankui's time
                        timePart,                // time extracted from Fankui's time
                        "待定",                  // gridStaff (placeholder)
                        fankui.getReturnperson() // reporter
                ));
            }
        } else {
            System.out.println("未找到 FankuiData.txt 或文件为空。尝试从默认 AQI 数据文件 (fankui.txt) 加载。");
            // Fallback: If FankuiData.txt is empty or doesn't exist, try to read from fankui.txt
            List<AqiData> loadedAqiData = AqiDataFileUtil.readAqiDataFromFile();

            if (loadedAqiData.isEmpty()) {
                System.out.println("默认 AQI 数据文件 (fankui.txt) 也为空或不存在。正在生成初始模拟数据。");
                // If fankui.txt is also empty, generate initial mock AqiData
                loadedAqiData = generateInitialMockData(); // Generate initial mock data
                AqiDataFileUtil.writeAqiDataToFile(loadedAqiData); // Save this initial data to fankui.txt
                System.out.println("已将生成的初始AQI模拟数据保存到 fankui.txt 文件。");
            } else {
                System.out.println("已从默认 AQI 数据文件 (fankui.txt) 加载AQI数据。");
            }
            dataToLoadIntoTable.addAll(loadedAqiData);
        }

        // Add all processed data to the master ObservableList
        masterAqiData.addAll(dataToLoadIntoTable);

        // Display all data initially in the TableView
        aqiTable.setItems(masterAqiData);
        // -------------------------------------------

        // Set up event handlers for buttons
        if (queryButton != null) {
            queryButton.setOnAction(event -> queryAqiData());
        } else {
            System.err.println("queryButton is null. Check FXML fx:id.");
        }
        if (clearButton != null) {
            clearButton.setOnAction(event -> clearFilters());
        } else {
            System.err.println("clearButton is null. Check FXML fx:id.");
        }

        if (saveButton != null) {
            saveButton.setOnAction(event -> handleSaveButton());
        }
    }

    // Example handler for a save button (if you want to save modifications made in the UI)
    @FXML
    private void handleSaveButton() {
        // This will save the CURRENT state of masterAqiData back to the ORIGINAL fankui.txt file.
        // If data was initially loaded from FankuiData.txt and converted, saving here will
        // save the AqiData representation back into fankui.txt.
        AqiDataFileUtil.writeAqiDataToFile(new ArrayList<>(masterAqiData));
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("保存成功");
        alert.setHeaderText(null);
        alert.setContentText("AQI数据已保存到文件 (fankui.txt)。");
        alert.showAndWait();
    }


    private void queryAqiData() {
        ObservableList<AqiData> filteredData = FXCollections.observableArrayList();

        // Get filter criteria
        String selectedProvince = cmbProvince2.getValue();
        String selectedCity = cmbCity2.getValue();
        LocalDate selectedDate = datePicker.getValue();

        // Apply filters to the masterAqiData
        for (AqiData data : masterAqiData) {
            boolean matchesProvince = (selectedProvince == null || selectedProvince.isEmpty()) || data.getProvince().equals(selectedProvince);
            boolean matchesCity = (selectedCity == null || selectedCity.isEmpty()) || data.getCity().equals(selectedCity);
            boolean matchesDate = (selectedDate == null) || data.getDate().equals(selectedDate.toString());

            if (matchesProvince && matchesCity && matchesDate) {
                filteredData.add(data);
            }
        }

        // Update the table to show filtered data
        aqiTable.setItems(filteredData);

        if (filteredData.isEmpty()) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("查询结果");
            alert.setHeaderText(null);
            alert.setContentText("没有找到符合筛选条件的数据。");
            alert.showAndWait();
        }
    }


    @FXML
    private void clearFilters() {
        cmbProvince2.getSelectionModel().clearSelection();
        cmbCity2.getSelectionModel().clearSelection();
        cmbCity2.setItems(FXCollections.observableArrayList()); // Clear city choices
        datePicker.setValue(null); // Clear the date picker
        // --- DISPLAY ALL DATA AFTER CLEARING FILTERS ---
        aqiTable.setItems(masterAqiData); // Show the full master list
        // ------------------------------------------------
    }

    // Helper method to generate initial mock data for first run if file is empty
    // This method is now only called if neither FankuiData.txt nor fankui.txt have data.
    private List<AqiData> generateInitialMockData() {
        List<AqiData> data = new ArrayList<>();

        data.add(new AqiData("1", "辽宁省", "沈阳市", "优", "2025-06-18", "08:30", "张三", "康丁友"));
        data.add(new AqiData("2", "山西省", "太原市", "良", "2025-06-18", "09:00", "王五", "康丁友"));
        data.add(new AqiData("3", "湖南省", "长沙市", "轻度污染", "2025-06-19", "10:15", "臧", "康丁友"));
        data.add(new AqiData("4", "吉林省", "长春市", "良", "2025-06-19", "11:00", "李四", "康丁友"));
        data.add(new AqiData("5", "辽宁省", "大连市", "优", "2025-06-20", "12:30", "赵六", "康丁友"));
        data.add(new AqiData("6", "山西省", "吕梁市", "中度污染", "2025-06-20", "14:00", "钱七", "康丁友"));
        data.add(new AqiData("7", "湖南省", "湘潭市", "良", "2025-06-21", "09:45", "孙八", "康丁友"));
        data.add(new AqiData("8", "吉林省", "吉林市", "轻度污染", "2025-06-21", "13:20", "周九", "康丁友"));
        data.add(new AqiData("9", "辽宁省", "铁岭市", "重度污染", "2025-06-22", "16:00", "吴十", "康丁友"));
        data.add(new AqiData("10", "山西省", "大同市", "优", "2025-06-22", "07:10", "郑一", "康丁友"));
        data.add(new AqiData("11", "湖南省", "衡阳市", "良", "2025-06-23", "18:00", "王二", "康丁友"));
        data.add(new AqiData("12", "辽宁省", "抚顺市", "轻度污染", "2025-06-23", "20:00", "李三", "康丁友"));
        data.add(new AqiData("13", "吉林省", "四平市", "中度污染", "2025-06-24", "06:30", "赵四", "康丁友"));
        data.add(new AqiData("14", "山西省", "运城市", "严重污染", "2025-06-24", "09:15", "钱五", "康丁友"));
        data.add(new AqiData("15", "湖南省", "怀化市", "良", "2025-06-25", "11:50", "孙六", "康丁友"));

        return data;
    }
}